/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ec.socialfun.filtros;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;

/**
 *
 * @author jorge
 */
public class FiltroDoubleLogin implements Filter {

    public static final String SESSIONS_KEY = "SESSIONS_KEY";
    private static final Logger log = Logger.getLogger(FiltroDoubleLogin.class.getName());
    private static final String PAGINA_DOBLE_LOGIN = "/doubleLoginError.jsp";
    private FilterConfig config;

    public FiltroDoubleLogin() {
        super();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config = filterConfig;
        ServletContext servletContext = this.config.getServletContext();
        HashMap hasMap = new HashMap();
        servletContext.setAttribute(FiltroDoubleLogin.SESSIONS_KEY, Collections.synchronizedMap(hasMap));
    }

    @Override
    public void doFilter(ServletRequest sr, ServletResponse sresp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) sr;
        String usuarioRemoto = servletRequest.getRemoteUser();

        if (usuarioRemoto == null) {
            filterChain.doFilter(sr, sresp);
            return;
        }

        usuarioRemoto = usuarioRemoto.toUpperCase();
        ServletContext servletContext = this.config.getServletContext();
        Map mapa = (Map) servletContext.getAttribute(FiltroDoubleLogin.SESSIONS_KEY);
        String usuarioRemotoMap = (String) mapa.get(usuarioRemoto);
        String sessionId = servletRequest.getSession().getId();
        if (usuarioRemotoMap == null) {
            ((Map) servletContext.getAttribute(FiltroDoubleLogin.SESSIONS_KEY)).put(usuarioRemoto, sessionId);
            filterChain.doFilter(sr, sresp);
            return;
        }

        if (usuarioRemotoMap.equals(sessionId)) {
            filterChain.doFilter(sr, sresp);
            return;
        }

        RequestDispatcher requestDispacher = sr.getRequestDispatcher(PAGINA_DOBLE_LOGIN);
        requestDispacher.forward(servletRequest, sresp);
    }

    @Override
    public void destroy() {

        this.config = null;
    }
}
